package com.link.base.tencent.corpwx.appchat.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.link.base.tencent.corpwx.message.model.MessageMpNews;
import com.link.base.tencent.corpwx.message.model.MessageNews;
import com.link.base.tencent.corpwx.message.util.AgentMessageUtil;
import com.link.base.wechat.basic.util.WxExceptionUtil;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.util.HttpRequestUtil;
import org.apache.commons.lang.StringUtils;

import java.util.List;

/**
 * 会话消息工具类
 * 
 * @author 欧阳振强
 * @date 2020/01/03
 */
public class AppChatUtil {
    /**群聊会话最小成员数量*/
    private static final int APP_CHAT_MIN_USER_NUM = 2;
    /**群聊会话最大成员数量*/
    private static final int APP_CHAT_MAX_USER_NUM = 500;
    /**创建群聊会话接口*/
    private static final String APP_CHAT_CREATE_API = "https://qyapi.weixin.qq.com/cgi-bin/appchat/create?access_token=ACCESS_TOKEN";
    /**修改群聊会话接口*/
    private static final String APP_CHAT_UPDATE_API = "https://qyapi.weixin.qq.com/cgi-bin/appchat/update?access_token=ACCESS_TOKEN";
    /**获取群聊会话接口*/
    private static final String APP_CHAT_GET_API = "https://qyapi.weixin.qq.com/cgi-bin/appchat/get?access_token=ACCESS_TOKEN&chatid=CHATID";
    /**群聊消息推送*/
    private static final String APP_CHAT_SEND_MESSAGE_API = "https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token=ACCESS_TOKEN";

    /**
     * 创建群聊会话
     * 
     * @author 欧阳振强
     * @date 2020/01/03
     * @param accessToken 接口凭证
     * @param chatName 群聊名称
     * @param userList 群聊成员列表
     * @param owner 群主用户Id【非必填】
     * @param chatId 群聊Id【非必填】
     */
    public static JSONObject createAppChat(String accessToken, String chatName, List<String> userList, String owner, String chatId) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        if (userList == null ) {
            throw new BasicServiceException("请传入成员列表！");
        } else {
            if (userList.size() <= APP_CHAT_MIN_USER_NUM) {
                throw new BasicServiceException("群成员Id列表不能小于" + APP_CHAT_MIN_USER_NUM + "！");
            }
            if (userList.size() > APP_CHAT_MAX_USER_NUM) {
                throw new BasicServiceException("群成员Id列表不能大于" + APP_CHAT_MAX_USER_NUM + "！");
            }
        }
        if (StringUtils.isBlank(chatName)) {
            throw new BasicServiceException("群聊名不能为空！");
        }
        String url = APP_CHAT_CREATE_API.replace("ACCESS_TOKEN", accessToken);
        JSONObject obj = new JSONObject();
        obj.put("name", chatName);
        obj.put("userlist", userList);
        if (StringUtils.isNotBlank(owner)) {
            obj.put("owner", owner);
        }
        if (StringUtils.isNotBlank(chatId)) {
            obj.put("chatid", chatId);
        }
        String param = obj.toJSONString();
        String resultStr = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 修改群聊会话
     *
     * @author 欧阳振强
     * @date 2020/01/03
     * @param accessToken 接口凭证
     * @param chatId 群聊Id
     * @param chatName 群聊名称【非必填】
     * @param addUserList 添加群聊成员列表【非必填】
     * @param delUserList 删除群聊成员列表【非必填】
     * @param owner 群主用户Id【非必填】
     */
    public static JSONObject updateAppChat(String accessToken, String chatId, String chatName,
                                           List<String> addUserList, List<String> delUserList, String owner) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        if (StringUtils.isBlank(chatId)) {
            throw new BasicServiceException("群聊Id不能为空！");
        }
        String url = APP_CHAT_UPDATE_API.replace("ACCESS_TOKEN", accessToken);
        JSONObject obj = new JSONObject();
        obj.put("chatid", chatId);
        if (StringUtils.isNotBlank(chatName)) {
            obj.put("name", chatName);
        }
        if (addUserList != null && addUserList.size() > 0) {
            obj.put("add_user_list", addUserList);
        }
        if (delUserList != null && delUserList.size() > 0) {
            obj.put("del_user_list", delUserList);
        }
        if (StringUtils.isNotBlank(owner)) {
            obj.put("owner", owner);
        }
        String param = obj.toJSONString();
        String resultStr = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(resultStr);
    }
    
    /**
     * 获取群聊会话
     * 
     * @author 欧阳振强
     * @date 2020/01/03
     * @param accessToken 接口凭证
     * @param chatId 群聊Id
     */
    public static JSONObject getAppChat(String accessToken,  String chatId) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        if (StringUtils.isBlank(chatId)) {
            throw new BasicServiceException("群聊Id不能为空！");
        }
        String url = APP_CHAT_GET_API.replace("ACCESS_TOKEN", accessToken).replace("CHATID", chatId);
        String resultStr = HttpRequestUtil.sendGet(url, "");
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 群聊会话 - 发送文本消息
     *
     * @author 欧阳振强
     * @date 2020/01/03
     * @param accessToken 接口凭证
     * @param chatId 群聊Id
     * @param content 文本信息
     */
    public static JSONObject sendAppChatText(String accessToken, String chatId, String content) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        if (StringUtils.isBlank(content)) {
            throw new BasicServiceException("文本信息不能为空！");
        }
        String url = APP_CHAT_SEND_MESSAGE_API.replace("ACCESS_TOKEN", accessToken);
        JSONObject obj = getBaseAppChatMsgJSON(chatId);
        obj.put("msgtype", "text");
        JSONObject textObj = new JSONObject();
        textObj.put("content", content);
        obj.put("text", textObj);
        String param = obj.toJSONString();
        String resultStr = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 群聊会话 - 发送图片消息
     *
     * @author 欧阳振强
     * @date 2020/01/03
     * @param accessToken 接口凭证
     * @param chatId 群聊Id
     * @param mediaId 图片媒体文件Id
     */
    public static JSONObject sendAppChatImage(String accessToken, String chatId, String mediaId) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        if (StringUtils.isBlank(mediaId)) {
            throw new BasicServiceException("图片媒体文件Id不能为空！");
        }
        String url = APP_CHAT_SEND_MESSAGE_API.replace("ACCESS_TOKEN", accessToken);
        JSONObject obj = getBaseAppChatMsgJSON(chatId);
        obj.put("msgtype", "image");
        JSONObject imageObj = new JSONObject();
        imageObj.put("media_id", mediaId);
        obj.put("image", imageObj);
        String param = obj.toJSONString();
        String resultStr = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 群聊会话 - 发送语音消息
     *
     * @author 欧阳振强
     * @date 2020/01/03
     * @param accessToken 接口凭证
     * @param chatId 群聊Id
     * @param mediaId 语音文件Id
     */
    public static JSONObject sendAppChatVoice(String accessToken, String chatId, String mediaId) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        if (StringUtils.isBlank(mediaId)) {
            throw new BasicServiceException("语音文件Id不能为空！");
        }
        String url = APP_CHAT_SEND_MESSAGE_API.replace("ACCESS_TOKEN", accessToken);
        JSONObject obj = getBaseAppChatMsgJSON(chatId);
        obj.put("msgtype", "voice");
        JSONObject voiceObj = new JSONObject();
        voiceObj.put("media_id", mediaId);
        obj.put("voice", voiceObj);
        String param = obj.toJSONString();
        String resultStr = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 群聊会话 - 发送视频消息
     *
     * @author 欧阳振强
     * @date 2020/01/03
     * @param accessToken 接口凭证
     * @param chatId 群聊Id
     * @param mediaId 视频媒体文件Id
     * @param title 视频消息标题
     * @param description 视频消息描述
     */
    public static JSONObject sendAppChatVideo(String accessToken, String chatId, String mediaId, String title, String description) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        if (StringUtils.isBlank(mediaId)) {
            throw new BasicServiceException("视频媒体文件Id不能为空！");
        }
        String url = APP_CHAT_SEND_MESSAGE_API.replace("ACCESS_TOKEN", accessToken);
        JSONObject obj = getBaseAppChatMsgJSON(chatId);
        obj.put("msgtype", "video");
        JSONObject videoObj = new JSONObject();
        videoObj.put("media_id", mediaId);
        videoObj.put("description", description);
        videoObj.put("title", title);
        obj.put("video", videoObj);
        String param = obj.toJSONString();
        String resultStr = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 群聊会话 - 发送文件消息
     *
     * @author 欧阳振强
     * @date 2020/01/03
     * @param accessToken 接口凭证
     * @param chatId 群聊Id
     * @param mediaId 文件Id
     */
    public static JSONObject sendAppChatFile(String accessToken, String chatId, String mediaId) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        if (StringUtils.isBlank(mediaId)) {
            throw new BasicServiceException("文件Id不能为空！");
        }
        String url = APP_CHAT_SEND_MESSAGE_API.replace("ACCESS_TOKEN", accessToken);
        JSONObject obj = getBaseAppChatMsgJSON(chatId);
        obj.put("msgtype", "file");
        JSONObject fileObj = new JSONObject();
        fileObj.put("media_id", mediaId);
        obj.put("file", fileObj);
        String param = obj.toJSONString();
        String resultStr = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 群聊会话 - 发送文本卡片消息
     *
     * @author 欧阳振强
     * @date 2020/01/03
     * @param accessToken 接口凭证
     * @param chatId 群聊Id
     * @param title 标题
     * @param description 描述
     * @param msgUrl 点击后跳转的链接
     * @param btnTxt 按钮文字
     */
    public static JSONObject sendAppChatFile(String accessToken, String chatId, String title,
                                             String description, String msgUrl, String btnTxt) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        if (StringUtils.isBlank(title)) {
            throw new BasicServiceException("标题不能为空！");
        }
        if (StringUtils.isBlank(description)) {
            throw new BasicServiceException("描述不能为空！");
        }
        if (StringUtils.isBlank(msgUrl)) {
            throw new BasicServiceException("点击后跳转的链接不能为空！");
        }
        String url = APP_CHAT_SEND_MESSAGE_API.replace("ACCESS_TOKEN", accessToken);
        JSONObject obj = getBaseAppChatMsgJSON(chatId);
        obj.put("msgtype", "textcard");
        JSONObject textCardObj = new JSONObject();
        textCardObj.put("title", title);
        textCardObj.put("description", description);
        textCardObj.put("url", msgUrl);
        textCardObj.put("btntxt", btnTxt);
        obj.put("textcard", textCardObj);
        String param = obj.toJSONString();
        String resultStr = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 群聊会话 - 发送图文消息
     *
     * @author 欧阳振强
     * @date 2020/01/03
     * @param accessToken 接口凭证
     * @param chatId 群聊Id
     * @param messageNewsList 图文消息列表
     */
    public static JSONObject sendAppChatNews(String accessToken, String chatId, List<MessageNews> messageNewsList) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        if (messageNewsList == null || messageNewsList.size() <= 0) {
            throw new BasicServiceException("请传入图文消息列表！");
        }
        String url = APP_CHAT_SEND_MESSAGE_API.replace("ACCESS_TOKEN", accessToken);
        JSONObject obj = getBaseAppChatMsgJSON(chatId);
        obj.put("msgtype", "news");
        JSONArray articles = new JSONArray();
        for (MessageNews item: messageNewsList) {
            // 返回article
            articles.add(AgentMessageUtil.getNewsJSON(item));
        }
        JSONObject newsObj = new JSONObject();
        newsObj.put("articles", articles);
        obj.put("news", newsObj);
        String param = obj.toJSONString();
        String resultStr = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 群聊会话 - 发送图文消息（mpnews）
     *
     * @author 欧阳振强
     * @date 2020/01/03
     * @param accessToken 接口凭证
     * @param chatId 群聊Id
     * @param messageMpNewsList 图文消息（mpnews）列表
     */
    public static JSONObject sendAppChatMpNews(String accessToken, String chatId, List<MessageMpNews> messageMpNewsList) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        if (messageMpNewsList == null || messageMpNewsList.size() <= 0) {
            throw new BasicServiceException("请传入图文消息列表！");
        }
        String url = APP_CHAT_SEND_MESSAGE_API.replace("ACCESS_TOKEN", accessToken);
        JSONObject obj = getBaseAppChatMsgJSON(chatId);
        obj.put("msgtype", "mpnews");
        JSONArray articles = new JSONArray();
        for (MessageMpNews item: messageMpNewsList) {
            // 返回article
            articles.add(AgentMessageUtil.getMpNewsJSON(item));
        }
        JSONObject newsObj = new JSONObject();
        newsObj.put("articles", articles);
        obj.put("mpnews", newsObj);
        String param = obj.toJSONString();
        String resultStr = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(resultStr);
    }


    /**
     * 构造基础会话消息发送JSON对象
     *
     * @author 欧阳振强
     * @date 2020/01/03
     * @param chatId 群聊Id
     */
    public static JSONObject getBaseAppChatMsgJSON(String chatId) throws Exception {
        JSONObject obj = new JSONObject();
        if (StringUtils.isBlank(chatId)) {
            throw new BasicServiceException("群聊Id不能为空！");
        }
        obj.put("chatid", chatId);
        obj.put("safe", "0");
        return obj;
    }
}

